package com.lifuixng.picturebackend.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lifuixng.picturebackend.common.DeleteRequest;
import com.lifuixng.picturebackend.constant.UserConstant;
import com.lifuixng.picturebackend.exception.BusinessException;
import com.lifuixng.picturebackend.exception.ErrorCode;
import com.lifuixng.picturebackend.exception.ThrowUtils;
import com.lifuixng.picturebackend.model.dto.user.*;
import com.lifuixng.picturebackend.model.entity.Picture;
import com.lifuixng.picturebackend.model.entity.User;
import com.lifuixng.picturebackend.model.enums.PictureReviewStatusEnum;
import com.lifuixng.picturebackend.model.enums.UserRoleEnum;
import com.lifuixng.picturebackend.model.mapping.UserMapping;
import com.lifuixng.picturebackend.model.vo.user.UserLoginVO;
import com.lifuixng.picturebackend.model.vo.user.UserVO;
import com.lifuixng.picturebackend.service.UserService;
import com.lifuixng.picturebackend.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author 26966
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2024-12-14 14:09:16
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapping userMapping;

    /**
     * 用户注册
     *
     * @param userRegisterRequest request
     * @return 1
     */
    @Override
    public Long userRegister(UserRegisterRequest userRegisterRequest) {

        // 校验
        if (StrUtil.hasBlank(
                userRegisterRequest.getUserAccount(),
                userRegisterRequest.getUserPassword(),
                userRegisterRequest.getCheckPassword())
        ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userRegisterRequest.getUserAccount().length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号长度不能小于4");
        }
        if (userRegisterRequest.getUserPassword().length() < 8 || userRegisterRequest.getCheckPassword().length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码过短");
        }
        if (!userRegisterRequest.getUserPassword().equals(userRegisterRequest.getCheckPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }

        // 查看数据库是否有该账号
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userRegisterRequest.getUserAccount());
        Long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已存在！");
        }

        // 加密密码
        String password = getEncryptPassword(userRegisterRequest.getUserPassword());
        // 添加
        User user = User.builder()
                .userAccount(userRegisterRequest.getUserAccount())
                .userPassword(password)
                .userRole(UserRoleEnum.USER.getValue())
                .userName("无名")
                .userAvatar(UserConstant.DEFAULT_AVATAR)
                .build();
        boolean result = this.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败！");
        }

        return user.getId();
    }

    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "lifuxing";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest request
     * @return vo
     */
    @Override
    public UserLoginVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {

        // 校验
        if (StrUtil.hasBlank(userLoginRequest.getUserAccount(), userLoginRequest.getUserPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码为空！");
        }
        if (userLoginRequest.getUserAccount().length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userLoginRequest.getUserPassword().length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }

        // 查数据库
        String password = getEncryptPassword(userLoginRequest.getUserPassword());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userLoginRequest.getUserAccount());
        queryWrapper.eq("userPassword", password);
        User user = this.baseMapper.selectOne(queryWrapper);
        if (user == null) {
            log.info("用户登录失败，该用户不存在！");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码错误！");
        }

        // 用户登录成功，将信息放到session中
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);

        // 脱敏 返回VO
        return userMapping.userToUserLoginVO(user);
    }

    @Override
    public User userLoginInfo(HttpServletRequest request) {
        UserLoginVO userLoginVO = this.getLoginUser(request);
        return userMapping.userLoginVOToUser(userLoginVO);

    }


    /**
     * 获取登录的用户信息
     *
     * @param request request
     * @return VO
     */
    @Override
    public UserLoginVO getLoginUser(HttpServletRequest request) {
        // 在session中取出
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        if (user == null || user.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        user = this.getById(user.getId());
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        return userMapping.userToUserLoginVO(user);
    }


    /**
     * 退出登录（用户注销）
     *
     * @param request request
     * @return b
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {

        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }


    /**
     * 将查询条件封装到条件构造器中
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.like(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 添加User
     *
     * @param userAddRequest userAdd
     * @return i
     */
    @Override
    public int addUser(UserAddRequest userAddRequest) {

        User user = userMapping.userAddRequestToUser(userAddRequest);
        user.setUserPassword(getEncryptPassword(UserConstant.DEFAULT_PASSWORD));
        int result = this.baseMapper.insert(user);
        if (result <= 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return result;
    }

    @Override
    public int deleteById(DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = this.baseMapper.deleteById(deleteRequest.getId());
        if (result <= 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return result;
    }

    @Override
    public int updateUser(UserUpdateRequest userUpdateRequest) {

        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User user = userMapping.userUpdateRequestToUser(userUpdateRequest);
        int result = this.baseMapper.updateById(user);
        if (result <= 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return result;

    }

    /**
     * 根据id获取用户信息
     *
     * @param id
     * @return
     */
    @Override
    public User getUserById(Long id) {

        if (id == null || id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        return this.getById(id);
    }

    /**
     * 根据id获取用户信息（脱敏）
     *
     * @param id
     * @return
     */
    @Override
    public UserVO getUserVOById(Long id) {

        User user = this.getById(id);
        return userMapping.userToUserVO(user);
    }

    /**
     * 用户列表 分页展示
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public Page<UserVO> userListByPage(UserQueryRequest userQueryRequest) {

        int current = userQueryRequest.getCurrent();
        int pageSize = userQueryRequest.getPageSize();
        // 开启分页，根据条件查询分页信息
        Page<User> userPage = this.page(new Page<>(current, pageSize), this.getQueryWrapper(userQueryRequest));
        // 将userList转换成userVOList
        List<UserVO> userVOList = userMapping.userListToUserVOList(userPage.getRecords());

        // 开启分页存放 userVoList
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        return userVOPage.setRecords(userVOList);
    }

    /**
     * 判断该用户是否为管理员角色
     *
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR);

        // 当前用户的角色是管理员就返回true
        if (user.getUserRole().equals(UserRoleEnum.ADMIN.getValue())){
            return true;
        }
        return false;
    }

}




